package com.yunqian.util.bean;

import com.yunqian.exception.BaseException;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author czy
 * @describe
 * @date 2018/7/3
 */
public class BeanMapUtil {

    /**
     * javaBean 转 Map
     *
     * @param object 需要转换的javabean
     * @return 转换结果map
     * @throws Exception
     */
    public static Map<String, Object> beanToMap(Object object) {
        Map<String, Object> map = null;
        try {
            map = new HashMap(16);
            Class cls = object.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(object));
            }
        } catch (Exception e) {
            throw new BaseException("bean to map fail");
        }
        return map;
    }

    /**
     * @param map 需要转换的map
     * @param cls 目标javaBean的类对象
     * @return 目标类object
     * @throws Exception
     */
    public static Object mapToBean(Map<String, ? extends Object > map, Class cls) {
        Object object = null;
        Boolean flag = false;
        try {
            Field[] fields = cls.getDeclaredFields();
            object = cls.newInstance();
            for (String key : map.keySet()) {
                flag = false;
                for (Field field : fields) {
                    if(field.getName().equals(key)){
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    Field temField = cls.getDeclaredField(key);
                    temField.setAccessible(true);
                    temField.set(object, map.get(key));
                }
            }
        } catch (Exception e) {
            throw new BaseException("map to bean fail");
        }
        return object;
    }
}
